/* 与 Notice 通信类
 * */
function JCChat(url) {
  this.url = url
  this.ws = undefined
  this.status = undefined
  this.listener = undefined
  this.init()
}

JCChat.prototype.init = function() {
  if (this.status && this.ws) { return false }

  if (this.url.indexOf('ws') < 0) {
    this.url = String.format('ws://{0}', this.url)
  }
  try {
    if (typeof (this.status) === 'undefined') {
      this.ws = new WebSocket(String.format('{0}&s=true', this.url))
    } else {
      this.ws = new WebSocket(this.url)
    }
  } catch (ex) {
    this.ws = undefined
    return false
  }

  var _this = this
  this.ws.onopen = function() { _this.stateChange(1) }
  this.ws.onmessage = function(event) { _this.receive(event && event.data) }
  this.ws.onclose = function(event) { _this.stateChange(0) }
  return true
}

JCChat.prototype.stateChange = function(b) {
  var _that = this
  this.status = b
  if (!b) {
    console.log('chat offline')
    this.ws = undefined
    if (!this.time) {
      this.time = window.setInterval(_that.init(), 5000)
    }
  } else {
    if (this.time) {
      window.clearInterval(this.time)
      this.time = undefined
    }
    console.log('chat online')
  }
}

JCChat.prototype.registListener = function(listener) {
  this.listener = listener
}
JCChat.prototype.clearListener = function() {
  this.listener = undefined
}
JCChat.prototype.receive = function(msg) {
  console.log('chat msg', msg)
  if (this.listener) {
    this.listener(msg)
  }
}

export default JCChat
